﻿using System;
using System.Collections.Generic;
//
using PerceptiveMCAPI.Export.Types;
//
namespace PerceptiveMCAPI.Export
{
	public class list
	{
		private listInput Input { get; set; }
		private listOutput Output { get; set; }
		// =============================================== constructors
		public list() { }
		// ---------
		public list( listInput input ) { this.Input = input; }
		// ===============================================  Execute
		public listOutput Execute()
		{
			// empty constructor & Execute() is bad
			if ( Input == null )
				throw new ArgumentException( "Input class not provided" );
			// do the deed
			Output = Execute( Input );
			return Output;
		}
		// ---------------------------------------------
		public listOutput Execute( listInput input )
		{
			Input = input;
			Output = new listOutput( Input );
			bool ValidationIsOK = true;
			//------------------------- validate it
			if ( Input.api_Validate )
			{
				Output.api_ValidatorMessages = list_ValidateInput.Validate( Input );
				ValidationIsOK = ValidateInput.IsOK( Output.api_ValidatorMessages );
			}
			//------------------------- do it
			if ( ValidationIsOK )
			{
				ExecuteRequest();
			}
			// ---
			return Output;
		}

		#region ---------------------------------------------------------- Do Export

		public void ExecuteRequest()
		{
			try
			{
				Dictionary<string, string> dict = new Dictionary<string, string>();
				dict.Add( "apikey", Input.parms.apikey );
				dict.Add( "id", Input.parms.id );
				dict.Add( "status", Input.parms.status.ToString() );
				// -- since
				if ( Input.parms.since > DateTime.MinValue )
				{
					dict.Add( "since", apiHelper.FormatApiDateParm( Input.parms.since ) );
				}
				// -- segment
				if ( Input.parms.segment.conditions.Count > 0 )
				{
					dict.Add( "segment[match]", Input.parms.segment.match );

					int i = -1;
					foreach (listSegmentOptions.listSegmentCondition c in Input.parms.segment.conditions )
					{
						i++;
						dict.Add( string.Format( "segment[conditions][{0}][field]", i ), c.field ?? "" );
						dict.Add( string.Format( "segment[conditions][{0}][op]", i ), c.op ?? "" );
						dict.Add( string.Format( "segment[conditions][{0}][value]", i ), c.value ?? "" );
						if ( !string.IsNullOrEmpty( c.extra ) )
							dict.Add( string.Format( "segment[conditions][{0}][extra]", i ), c.extra );
					}
				}
				// -- do it
				string api_Request = "";
				List<string> api_Response = apiExport.ProcessRequest( Input, dict, out api_Request );
				Output.Format( api_Request, api_Response );
			}
			catch ( Exception ex )
			{
				Output.api_ErrorMessages.Add( apiException.FormatError( ex ) );
			}
		}
		#endregion
	}
}
